package 多线程.交替输出;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author : K k
 * @date : 22:59 2020/8/11
 * 通过AtomicInteger实现自旋锁
 */
public class Ans3AtomicIntegerCAS {
    static volatile AtomicInteger threadNo=new AtomicInteger(1);

    public static void main(String[] args) {
        char[] a1 = "1234567".toCharArray();
        char[] a2 = "ABCDEFG".toCharArray();
        new Thread(() -> {
            for (char c : a1) {
                while (threadNo.get()!=1) {} //线程竞争失败，while循环阻塞自己
                System.out.println(c);
                threadNo.set(2);
            }
        }).start();

        new Thread(() -> {
            for (char c : a2) {
                while (threadNo.get()!=2) {}
                System.out.println(c);
                threadNo.set(1);
            }
        }).start();

    }
}
